<template>
    <BasicLayout>
        <template #wrapper>
            <el-card class="box-card">
                <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
                    <el-form-item label="店铺名称" prop="storeName">
                        <el-input v-model="queryParams.storeName" placeholder="请输入店铺名称" clearable size="small"
                            @keyup.enter.native="handleQuery" />
                    </el-form-item>

                    <!--                    <el-form-item label="负责人" prop="userName">-->
                    <!--                        <el-input v-model="queryParams.userName" placeholder="请选择负责人" clearable size="small"-->
                    <!--                            @keyup.enter.native="handleQuery" />-->
                    <!--                    </el-form-item>-->
                    <el-form-item label="机构状态" prop="status">
                        <el-select v-model="queryParams.status" placeholder="关闭，未发布，发布" clearable size="small">
                            <el-option v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictLabel"
                                :value="dict.dictValue" />
                        </el-select>
                    </el-form-item>
                    <!--                    <el-form-item label="创建时间" prop="createdAt">-->
                    <!--                        <el-date-picker v-model="queryParams.createdAt" value-format="yyyy-MM-dd" type="daterange"-->
                    <!--                            range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" size="small"-->
                    <!--                            @keyup.enter.native="handleQuery"></el-date-picker>-->
                    <!--                    </el-form-item>-->
                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>

                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button v-permisaction="['edu:store:add']" type="primary" icon="el-icon-plus" size="mini"
                            @click="handleAdd">新增
                        </el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button v-permisaction="['edu:store:edit']" type="success" icon="el-icon-edit" size="mini"
                            :disabled="single" @click="handleUpdate">修改
                        </el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button v-permisaction="['edu:store:remove']" type="danger" icon="el-icon-delete" size="mini"
                            :disabled="multiple" @click="handleDelete">删除
                        </el-button>
                    </el-col>
                </el-row>

                <el-table v-loading="loading" :data="eduschoolList" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" align="center" />
                    <el-table-column label="机构头像" align="avatar" prop="center" :show-overflow-tooltip="true">
                        <template slot-scope="scope">
                            <el-avatar :size="50" :src="scope.row.avatar"></el-avatar>
                        </template>
                    </el-table-column>
                    <el-table-column label="店铺名称" align="center" prop="storeName" :show-overflow-tooltip="true" />
                    <!--                    <el-table-column label="负责人" align="center" prop="userName" :show-overflow-tooltip="true" />-->
                    <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat" width="100">
                        <template slot-scope="scope">
                            {{ statusFormat(scope.row) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="地址" align="center" prop="address" :show-overflow-tooltip="true" />
                    <el-table-column label="创建时间" align="center" prop="createdAt" :show-overflow-tooltip="true" />
                    <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                        <template slot-scope="scope">
                            <el-button v-permisaction="['edu:store:edit']" size="mini" type="text" icon="el-icon-edit"
                                @click="handleUpdate(scope.row)">修改
                            </el-button>
                            <el-button v-permisaction="['edu:store:remove']" size="mini" type="text"
                                icon="el-icon-delete" @click="handleDelete(scope.row)">删除
                            </el-button>
                            <!--                            <el-dropdown-->
                            <!--                                @command="handleCommand($event, scope.row)"-->
                            <!--                            >-->
                            <!--                                <span class="el-dropdown-link">-->
                            <!--                                    更多<i-->
                            <!--                                        class="el-icon-arrow-down el-icon&#45;&#45;right"-->
                            <!--                                    ></i>-->
                            <!--                                </span>-->
                            <!--                                <el-dropdown-menu slot="dropdown">-->
                            <!--                                    <el-dropdown-item command="course"-->
                            <!--                                        >课程管理</el-dropdown-item-->
                            <!--                                    >-->
                            <!--                                    <el-dropdown-item command="classroom"-->
                            <!--                                        >班级管理</el-dropdown-item-->
                            <!--                                    >-->
                            <!--                                </el-dropdown-menu>-->
                            <!--                            </el-dropdown>-->
                        </template>
                    </el-table-column>
                </el-table>

                <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageIndex"
                    :limit.sync="queryParams.pageSize" @pagination="getList" />

                <!-- 添加或修改对话框 -->
                <el-dialog :title="title" :visible.sync="open" width="500px">
                    <el-form ref="form" :model="form" :rules="rules" label-width="80px">

                        <el-form-item label="门店名称" prop="storeName">
                            <el-input v-model="form.storeName" placeholder="门店名称" :style="{ width: '195px' }" />
                        </el-form-item>
                        <el-form-item label="门店地址" prop="address">
                            <!-- <elMap></elMap> -->
                            <el-input suffix-icon="el-icon-position" v-model="form.address" @focus="visibleMap"
                                placeholder="门店地址" :style="{ width: '200px' }" />
                        </el-form-item>
                        <!-- <el-form-item label="门店地址" prop="address">
                            <el-input
                                v-model="form.address"
                                placeholder="address"
                                :style="{ width: '195px' }"
                            />
                        </el-form-item> -->
                        <el-form-item label="门店封面" prop="avatar">
                            <uploadImg :imgUrl.sync="form.avatar" :cut="false"></uploadImg>
                        </el-form-item>
                        <!--                        <el-form-item label="门店图片" prop="Image">-->
                        <!--                            <uploadImg :imgUrl.sync="form.image" :multiple="true" :cut="false"></uploadImg>-->
                        <!--                        </el-form-item>-->
                        <!--                        <el-form-item label="负责人" prop="userName">-->
                        <!--                            <el-input v-model="form.userName" placeholder="负责人姓名" :style="{ width: '195px' }" />-->
                        <!--                        </el-form-item>-->
                        <el-form-item label="门店电话" prop="telephone">
                            <el-input v-model="form.telephone" placeholder="门店电话" :style="{ width: '195px' }" />
                        </el-form-item>
                        <el-form-item label="营业时间" prop="time">
                            <el-time-picker is-range v-model="form.time" :picker-options="pickerOptions"
                                range-separator="至" start-placeholder="开始时间" @change="changeTime" end-placeholder="结束时间"
                                placeholder="选择时间范围">
                            </el-time-picker>
                        </el-form-item>
                        <el-form-item label="简介" prop="description">
                            <el-input type="textarea" :rows="5" placeholder="请输入简介" v-model="form.description">
                            </el-input>
                        </el-form-item>
                        <el-form-item label="时间间隔" prop="interval">
                            <el-input-number v-model="form.interval" placeholder="权重"></el-input-number>
                        </el-form-item>
                        <el-form-item label="预约时间" prop="time">
                            <el-time-picker is-range v-model="form.apptime" :picker-options="pickerOptions"
                                            range-separator="至" start-placeholder="开始时间" @change="changeTime1" end-placeholder="结束时间"
                                            placeholder="选择时间范围">
                            </el-time-picker>
                        </el-form-item>

                        <el-form-item label="状态关闭" prop="status">
                            <el-radio-group v-model="form.status">
                                <el-radio v-for="(item, index) in statusOptions" :key="index" :label="item.dictValue">
                                    {{ item.dictLabel }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="权重" prop="weigh">
                            <el-input-number v-model="form.weigh" placeholder="权重"></el-input-number>
                        </el-form-item>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button type="primary" @click="submitForm">确 定</el-button>
                        <el-button @click="cancel">取 消</el-button>
                    </div>
                </el-dialog>
            </el-card>
            <el-dialog title="设置地址" :visible.sync="showMap" width="800px" :before-close="handleClose">
                <elMap @getLocation="getLocation" :address="form.address"></elMap>
                <div slot="footer">
                    <el-button @click="showMap = false">取 消</el-button>
                    <el-button type="primary" @click="showMap = false">确 定</el-button>
                </div>
            </el-dialog>
        </template>
    </BasicLayout>
</template>

<style>
.el-dropdown-link {
    cursor: pointer;
    color: #409eff;
    font-size: 12px;
    margin-left: 10px;
}
.el-icon-arrow-down {
    font-size: 12px;
}
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}
.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
<script>
import {
    addEduSchool,
    delEduSchool,
    getEduSchool,
    listEduSchool,
    updateEduSchool
} from "@/api/edu/school";
import { getToken } from "@/utils/auth";
//老师选择器
import SelectTeacher from "@/views/edu/teacher/components/SelectTeacher";
import elMap from "@/components/elMap";
export default {
    name: "Config",
    components: {
        SelectTeacher,
        elMap
    },
    data () {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 总条数
            total: 0,
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            isEdit: false,
            // 类型数据字典
            typeOptions: [],
            eduschoolList: [],
            statusOptions: [],
            // 查询参数
            queryParams: {
                pageIndex: 1,
                pageSize: 10,
                createdAt: undefined,
                description: undefined,
                storeName: undefined,
                storeId: undefined,
                userName: undefined,
                status: undefined
            },
            // 表单参数
            form: {},
            pickerOptions: {
                // selectableRange: '18:30:00-20:30:00',
                // format: 'HH:mm',
                disabledDate (time) {
                    // return time.getTime() < Date.now() // 选当前时间之后的时间
                    // return time.getTime() > Date.now() // 选当前时间之前的时间
                }
            },
            // 表单校验
            rules: {
                description: [
                    {
                        required: true,
                        message: "简介不能为空",
                        trigger: "blur"
                    }
                ],
                storeName: [
                    {
                        required: true,
                        message: "标题不能为空",
                        trigger: "blur"
                    }
                ],
                userName: [
                    {
                        required: true,
                        message: "负责人不能为空",
                        trigger: "blur"
                    }
                ],
                status: [
                    {
                        required: true,
                        message: "机构状态不能为空",
                        trigger: "blur"
                    }
                ]
            },

            //上传
            uploadImageAction:
                process.env.VUE_APP_BASE_API + "/api/v1/common/uploadImage",
            myHeader: {
                Authorization: "Bearer " + getToken()
            },
            showMap: false
        };
    },
    created () {
        this.getList();
        // this.getDicts("edu_status").then((response) => {
        //   this.statusOptions = response.data;
        // });
        this.statusOptions = this.$store.getters.parameter.edu_status;
        console.log(this.statusOptions)
    },
    methods: {
        handleClose () {
            this.visibleMap();
        },
        visibleMap () {
            this.showMap = !this.showMap;
        },
        changeTime (e) {
            console.log(e)
            this.form.startTime = this.dateFormat(e[0])
            this.form.endTime = this.dateFormat(e[1])
        },
        changeTime1 (e) {
            console.log(e)
            this.form.appStartTime = this.dateFormat(e[0])
            this.form.appEndTime = this.dateFormat(e[1])
        },
        dateFormat (date) {
            let time = new Date(date);
            let hour = time.getHours().toString().padStart(2, '0')
            let min = time.getMinutes().toString().padStart(2, '0')
            let sec = time.getSeconds().toString().padStart(2, '0')
            return `${hour}:${min}:${sec}`
        },
        getLocation (e) {
            console.log(e)
            this.form.address = e.poi.district + e.poi.address;
            this.form.longitude = e.poi.location.lng
            this.form.latitude = e.poi.location.lat
        },
        // 按钮操作
        handleCommand (command, data) {

            if (command == "edit") {
                this.handleUpdate(data);
            }
            if (command == "del") {
                this.handleDelete(data);
            }
        },
        /** 查询参数列表 */
        getList () {
            this.loading = true;
            listEduSchool(
                this.addDateRange(this.queryParams, this.dateRange)
            ).then(response => {
                this.eduschoolList = response.data.list;
                this.total = response.data.count;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel () {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset () {
            this.form = {
                avatar: undefined,
                categoryId: undefined,
                description: undefined,
                storeName: undefined,
                storeId: undefined,
                userName: undefined,
                status: "draft",
                weigh: 1,
                image: undefined
            };
            this.resetForm("form");
        },
        statusFormat (row) {
            return this.selectDictLabel(this.statusOptions, row.status);
        },

        /** 搜索按钮操作 */
        handleQuery () {
            this.queryParams.pageIndex = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery () {
            this.dateRange = [];
            this.resetForm("queryForm");
            this.handleQuery();
        },
        /** 新增按钮操作 */
        handleAdd () {
            this.reset();
            this.open = true;
            this.title = "添加机构";
            this.isEdit = false;
        },
        // 多选框选中数据
        handleSelectionChange (selection) {
            this.ids = selection.map(item => item.storeId);
            this.single = selection.length !== 1;
            this.multiple = !selection.length;
        },
        /** 修改按钮操作 */
        handleUpdate (row) {
            this.reset();
            const storeId = row.storeId || this.ids;
            getEduSchool(storeId).then(response => {
                let form = response.data;
                // this.form.userName = '1,2'
                let startTime = response.data.startTime.split(':');
                let endTime = response.data.endTime.split(':');
                form.time = ['2021-02-17 ' + response.data.startTime, '2021-02-17 ' + response.data.endTime];
                let appStartTime = response.data.appStartTime.split(':');
                let appEndTime = response.data.appEndTime.split(':');
                form.apptime = ['2021-02-17 ' + response.data.appStartTime, '2021-02-17 ' + response.data.appEndTime];
                // form.time = [new Date(2021, 2, 17, Number(startTime[0]), Number(startTime[1])), new Date(2021, 2, 17, Number(endTime[0]), Number(endTime[1]))];
                this.form = form;
                console.log(this.form)
                this.open = true;
                this.title = "修改机构";
                this.isEdit = true;
                this.$forceUpdate();
            });
        },
        /** 提交按钮 */
        submitForm: function () {

            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.storeId !== undefined) {
                        updateEduSchool(this.form).then(response => {
                            if (response.code === 200) {
                                this.msgSuccess("修改成功");
                                this.open = false;
                                this.getList();
                            } else {
                                this.msgError(response.msg);
                            }
                        });
                    } else {
                        addEduSchool(this.form).then(response => {
                            if (response.code === 200) {
                                this.msgSuccess("新增成功");
                                this.open = false;
                                this.getList();
                            } else {
                                this.msgError(response.msg);
                            }
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete (row) {
            const Ids = row.storeId || this.ids;
            this.$confirm('是否确认删除编号为"' + Ids + '"的数据项?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(function () {
                    return delEduSchool(Ids);
                })
                .then(() => {
                    this.getList();
                    this.msgSuccess("删除成功");
                })
                .catch(function () { });
        },

        //图片上传 start

        handleRemove (file, fileList) {
            console.log(file, fileList);
            this.form.avatar = "";
            console.log(this.form.avatar);
        },

        //上传组图成功
        handlepostingImageSuccess (res, file) {
            console.log(res.data);
            if (res.code == "200") {
                this.form.avatar = res.data.url;
            }

            console.log(this.form.avatar);
        },
        beforeAvatarUpload (file) {
            const isJPG = file.type === "image/jpeg";
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error("上传头像图片只能是 JPG 格式!");
            }
            if (!isLt2M) {
                this.$message.error("上传头像图片大小不能超过 2MB!");
            }
            return isJPG && isLt2M;
        },

        //图片上传 end

        //接收用户IDs
        setTeacherIds: function (teacherIds) {
            // childValue就是子组件传过来的值
            // console.log("userIds: "+userIds);
            console.log("触发了");
            if (teacherIds && teacherIds[0]) {
                this.form.userName = teacherIds[0];
            }
        }
    }
};
</script>
